package com.github.caijh.mall.front.controller;

import java.io.IOException;
import java.util.Map;
import javax.inject.Inject;

import com.alibaba.fastjson.JSONObject;
import com.github.caijh.framework.core.exception.BizException;
import com.github.caijh.framework.web.controller.BaseController;
import com.github.caijh.mall.common.CommonResult;
import com.github.caijh.mall.common.MessageConstants;
import com.github.caijh.mall.front.service.QrCodeService;
import com.github.caijh.mall.front.vo.QrCodeHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api/front/qrcode")
@Api(tags = "二维码服务")
public class QrCodeController extends BaseController {

    @Inject
    private QrCodeService qrCodeService;

    @ApiOperation(value = "获取二维码")
    @PostMapping(value = "/get")
    public CommonResult<Map<String, Object>> get(@RequestBody JSONObject data) throws IOException {
        return CommonResult.success(qrCodeService.get(data));
    }

    @ApiOperation(value = "远程图片转base64")
    @PostMapping(value = "/base64")
    public CommonResult<Map<String, Object>> get(@RequestParam String url) {
        return CommonResult.success(qrCodeService.base64(url));
    }

    /**
     * 生成字符串的QRCode.
     *
     * @param text   字符串
     * @param width  图片宽度
     * @param height 图片高度
     * @return CommonResult
     */
    @ApiOperation(value = "将字符串 转base64")
    @PostMapping(value = "/str2base64")
    public CommonResult<QrCodeHolder> getQrcodeByString(
            @RequestParam String text,
            @RequestParam int width,
            @RequestParam int height) {
        if ((width < 50 || height < 50) && (width > 500 || height > 500) && text.length() >= 999) {
            throw BizException.of(MessageConstants.QRCODE_PARAMS_INVALID);
        }
        return CommonResult.success(qrCodeService.getQrCode(text, width, height));
    }

}



